require('shelljs/global');
const NodeSsh = require('node-ssh');
const path = require('path');
const os = require('os');
const ssh = new NodeSsh();
const fs = require('fs');

const checkDir = dir => {
  return `if [ ! -d ${dir} ]; then
  if [ -f ${dir} ]; then
    rm -rf ${dir}
  fi
  mkdir -p ${dir}
fi`;
};

const delExists = file => {
  return `if [ -f ${file} ]; then
  rm -rf ${file}
fi`;
};


async function exesh(pms, config, env, password){
  try{
    let files = [];
    if (!pms || pms.length == 0) {
      for (const file in config.files) {
        files.push(file);
      }
    } else {
      files = pms;
    }
    const tmpDir = config.tmpDir;
    const buildDir = config.outDir;
    let ecfg = null;
    for (const cfg of config.configs) {
      if (cfg.env == env) {
        ecfg = cfg;
        break;
      }
    }
    if (!ecfg) {
      throw new Error(`找${env}不到对应的配置`);
    }
    const sshCfg = {};
    sshCfg.host = ecfg.middleServer;
    sshCfg.username = ecfg.user;
    if (password) {
      ecfg.password = password;
    }
    if (ecfg.password) {
      sshCfg.password = ecfg.password;
    } else {
      const key = path.join(os.homedir(), '.ssh/id_rsa');
      sshCfg.privateKey = key;
    }
    try{
      await ssh.connect(sshCfg);
    }catch(e){
      console.error(e);
      exit(1);
    }
    await ssh.exec(checkDir(tmpDir));
    for (const file of files) {
      let fl = pwd() + '/' + file;
      if (!test('-f', fl)) {
        throw new Error(`找不到文件 ${fl}`);
      }
      console.log(`开始在${{test: '测试', prod: '正式'}[env] || env}环境 运行${file}`);
      try{
        await ssh.exec(fs.readFileSync(fl,'utf-8'),[],{
          onStdout(info){
            process.stdout.write(info.toString('utf8'));
          }
        });
      }catch(e){
        const info = e.toString().replace(/^Error:/,'').trim();
        if(info != 'Pseudo-terminal will not be allocated because stdin is not a terminal.'){
          throw e;
        }
      }
    }
    ssh.dispose();
  }catch (e){
    console.log(e);
    exit(1);
  }
}


module.exports = {
  exesh: exesh
};













